import { EnumMemberIdentity, JobType, Region } from "@/apis/endpoint/model";
import GpContainer from "@/components/GpContainer";
import GpFontIcon from "@/components/GpFontIcon";
import GpNavbar from "@/components/GpNavbar";
import { GpTouchableView } from "@/components/GpTouchableView";
import { NAVIGATION_BASE_LAYOUT } from "@/hooks/useLayout";
import { Button, Image, PickerView, PickerViewColumn, Text, View } from "@tarojs/components";
import clsx from "clsx";
import { useEffect, useMemo, useState } from "react";
import { useImmer } from "use-immer";
import { identityOptions } from "../enum-options";
import { navigate } from "@/utils/navigation";
import { pageMapper } from "@/constants/pageMap";
import { Popup, SafeArea } from "@taroify/core";
import { isSetValue } from "@/utils/helper";
import { postMyEdituserguideinfo } from "@/apis/endpoint/my";
import { useAuthStore } from "@/store";

interface State {
  identity?: EnumMemberIdentity
  jobTypeId?: number
  jobTypeName?: string
  salaryMax?: number
  salaryMin?: number
  cityId?: string
  cityName?: string
  lat?: number
  lng?: number
}

interface SalaryPannelState {
  salaryOpen?: boolean
  salaryValue?: number[]
  maxOptions: Array<IOption<number>>
  lock: boolean
}

export default function Index() {
  const allValue = -1
  const salaryColumns = useMemo(
    () => {
      const ranges = Array.from({length: 250}).map<IOption<number>>((_, i) => ({label: `${i+1}k`, value: i+1}))
      const allOption: IOption<number> = {label: '面议', value: allValue}
      return {
        min: [allOption, ...ranges],
        max: ranges,
        max_allvalue: [allOption],
      }
    },
    [],
  )
  const [navigationHeight, setNavigationHeight] = useState(NAVIGATION_BASE_LAYOUT.statusBarHeight + NAVIGATION_BASE_LAYOUT.navigationHeight)
  const [state, setState] = useImmer<State>({})
  const fulfilled = useMemo(() => {
    return (["identity", "jobTypeId", "cityId"/**, "lat", "lng" */] as const).every(field => isSetValue(state[field]))
  }, [state])
  const [salaryPannelState, setSalaryPannelState] = useImmer<SalaryPannelState>({
    salaryOpen: false,
    maxOptions: salaryColumns.max_allvalue,
    salaryValue: [0, 0],
    lock: false
  })
  const fetchMemberProfile = useAuthStore(state => state.fetchMemberProfile)
  useEffect(() => {
    fetchMemberProfile()
    .then(info => {
      setState(draft => {
        draft.cityId = info.cityId
        draft.cityName = info.cityName
        draft.identity = info.identity
        draft.jobTypeId = info.jobTypeId
        draft.jobTypeName = info.jobTypeName
        draft.lat = info.lat
        draft.lng = info.lng
        draft.salaryMax = info.salaryMax
        draft.salaryMin = info.salaryMin
      })
    })
  }, [])
  async function handleSave() {
    if (!fulfilled) return
    await postMyEdituserguideinfo({
      identity: state.identity!,
      cityId: state.cityId,
      jobTypeId: state.jobTypeId,
      lat: state.lat,
      lng: state.lng,
      salaryMax: state.salaryMax === allValue ? void 0 : state.salaryMax! * 1000,
      salaryMin: state.salaryMin === allValue ? void 0 : state.salaryMin! * 1000
    })
    await fetchMemberProfile()
    Taro.showToast({
      title: "保存成功",
      icon: "success"
    })
    navigate()
  }
  function handleEditJobType() {
    const query = state.jobTypeId ? {jobtypeid: state.jobTypeId} : null
    navigate(pageMapper.select.jobtype, query, "navigateTo", {
      events: {
        chooseJobType(value: JobType) {
          setState(draft => {
            draft.jobTypeId = value.id
            draft.jobTypeName = value.name
          })
        }
      }
    })
  }
  function handleEditCity() {
    const query = state.cityId ? {cityid: state.cityId} : null
    navigate(pageMapper.select.city, query, "navigateTo", {
      events: {
        chooseCity(value: Region) {
          setState(draft => {
            draft.cityId = value.id
            draft.cityName = value.name
            // TODO: 精度纬度
          })
        }
      }
    })
  }
  function handleSalaryOpen() {
    const { salaryMax, salaryMin } = state
    if (salaryMax && salaryMin) {
      const maxOptions = salaryMin === allValue ? salaryColumns.max_allvalue : salaryColumns.max
      const minIndex = salaryMin === allValue ? 0 : salaryColumns.min.findIndex(l => l.value === salaryMin)
      const maxIndex = salaryMin === allValue ? 0: maxOptions.findIndex(l => l.value === salaryMax)
      setSalaryPannelState(draft => {
        draft.maxOptions = maxOptions
        draft.salaryOpen = true
        draft.salaryValue = [minIndex, maxIndex]
      })
    } else {
      setSalaryPannelState(draft => {
        draft.maxOptions = salaryColumns.max_allvalue
        draft.salaryOpen = true
        draft.salaryValue = [0, 0]
      })
    }
  }
  function handleSalaryCancel() {
    setSalaryPannelState(draft => {
      draft.salaryOpen = false
    })
  }
  function handleSalaryConfirm() {
    if (salaryPannelState.lock) return
    if (!salaryPannelState.salaryValue) {
      handleSalaryCancel()
      return
    }
    const [minIndex, maxIndex] = salaryPannelState.salaryValue
    setState(draft => {
      draft.salaryMin = salaryColumns.min[minIndex].value
      draft.salaryMax = salaryPannelState.maxOptions[maxIndex].value
    })
    handleSalaryCancel()
  }
  function handleSalaryChange(value: number[]) {
    if (salaryPannelState.salaryOpen === false) return
    const [minIndex] = value
    setSalaryPannelState(draft => {
      if (minIndex === 0) {
        draft.salaryValue = [0, 0]
        draft.maxOptions = salaryColumns.max_allvalue
      } else {
        draft.salaryValue = value
        draft.maxOptions = salaryColumns.max
      }
    })
  }
  function renderSalaryPannel() {
    return (
      <View>
        <Popup open={salaryPannelState.salaryOpen} rounded placement="bottom" onClose={handleSalaryCancel}>
          <Popup.Backdrop />
          <View>
            <PickerView
              indicatorStyle="height: 50px;"
              style="width: 100%; height: 300px; background-color: #ffffff;"
              indicatorClass="text-primary font-medium text-[32px]"
              value={salaryPannelState.salaryValue}
              onChange={ev => handleSalaryChange(ev.detail.value)}
              onPickStart={() => setSalaryPannelState(draft => {draft.lock = true})}
              onPickEnd={() => setSalaryPannelState(draft => {draft.lock = false})}
            >
              <PickerViewColumn>
                {salaryColumns.min.map(l => {
                  return (
                    <View
                      key={l.value}
                      style={{
                        lineHeight: "50px",
                        textAlign: "center"
                      }}
                    >
                      {l.label}
                    </View>
                  )
                })}
              </PickerViewColumn>
              <PickerViewColumn>
                {salaryPannelState.maxOptions.map(l => {
                  return (
                    <View
                      key={l.value}
                      style={{
                        lineHeight: "50px",
                        textAlign: "center"
                      }}
                    >
                      {l.label}
                    </View>
                  )
                })}
              </PickerViewColumn>
            </PickerView>
          </View>
          <View className="flex flex-row justify-center items-center gap-[32px] pb-[64px] mt-[80px]">
            <GpTouchableView onClick={handleSalaryCancel} className="w-[248px] h-[80px] flex flex-row justify-center items-center bg-primary/10 rounded-[40px] text-primary text-[28px]">
              取消
            </GpTouchableView>
            <GpTouchableView onClick={handleSalaryConfirm} className={clsx("w-[248px] h-[80px] flex flex-row justify-center items-center bg-theme rounded-[40px] text-white text-[28px]", {
              "opacity-40": salaryPannelState.lock
            })}>
              确定
            </GpTouchableView>
          </View>
          <SafeArea position="bottom" />
        </Popup>
      </View>
    )
  }
  return (
    <GpContainer className="bg-[#F4F6FC]">
      <GpNavbar
        navigationBarTitleText={null}
        navigationBarBackgroundColor="transparent"
        navigationBarPlaceholder={false}
        onLayout={({statusBarHeight, navigationHeight}) => setNavigationHeight(statusBarHeight + navigationHeight)}
      />
      <View className="relative h-[400px] box-border">
        <Image src="/static/images/common/home-bg.png" className="absolute inset-0 w-full box-border block object-cover z-0" />
        <View className="relative w-full h-full box-border px-[32px]"
          style={{
            paddingTop: `${navigationHeight}px`
          }}
        >
          <View className="mt-[20px]">
            <Text className="text-primary font-bold text-[48px] leading-[48px]">想找什么工作？</Text>
          </View>
          <Text className="inline-block mt-[28px] text-[28px] text-third">需要你提供以下信息，用于为你提供岗位</Text>
        </View>
      </View>
      <View className="px-[32px] -mt-[32px] flex flex-row items-center gap-[30px]">
        {
          identityOptions.map(item => (
            <View key={item.value} className={clsx("flex-1 bg-white rounded-[24px] h-[176px] relative flex items-center pl-[40px]", {
              "border-2 border-solid border-theme": item.value === state.identity
            })} onClick={() => setState(draft => {draft.identity = item.value;})}>
              <Text className={clsx("text-[40px] font-bold", item.value === state.identity ? "text-theme" : "text-primary")}>{item.label}</Text>
              <Image src={item.value === EnumMemberIdentity.职场人 ? "/static/images/me/niuma.png" : "/static/images/me/shechu.png"} className="absolute top-0 right-0 bottom-0 h-full" mode="heightFix" />
            </View>
          ))
        }
      </View>
      <View className="mt-[32px] bg-white rounded-t-[48px]">
        <View className="pt-[64px] px-[60px] border-b-2 border-solid border-b-[#EEEEEE]">
          <Text className="text-[36px] text-primary font-bold">
            期望职位
          </Text>
          <View className="flex flex-row justify-between items-center mt-[30px] pb-[16px]" onClick={handleEditJobType}>
            <Text className={clsx("text-[28px]", state.jobTypeId ? "text-primary" : "text-placeholder")}>
              {state.jobTypeName || "请选择期望岗位"}
            </Text>
            <GpFontIcon name="icon-a-jiantou_youda" size={40} className="text-placeholder" />
          </View>
        </View>
        <View className="pt-[64px] px-[60px] border-b-2 border-solid border-b-[#EEEEEE]">
          <Text className="text-[36px] text-primary font-bold">
            工作城市
          </Text>
          <View className="flex flex-row justify-between items-center mt-[30px] pb-[16px]" onClick={handleEditCity}>
            <Text className={clsx("text-[28px]", state.cityId ? "text-primary" : "text-placeholder")}>
              {state.cityName || "请选择工作城市"}
            </Text>
            <GpFontIcon name="icon-a-jiantou_youda" size={40} className="text-placeholder" />
          </View>
        </View>
        <View className="pt-[64px] px-[60px] border-b-2 border-solid border-b-[#EEEEEE]">
          <Text className="text-[36px] text-primary font-bold">
            期望薪资
          </Text>
          <View className="flex flex-row justify-between items-center mt-[30px] pb-[16px]" onClick={handleSalaryOpen}>
            <Text className={clsx("text-[28px]", state.salaryMin && state.salaryMax ? "text-primary" : "text-placeholder")}>
              {
                state.salaryMin && state.salaryMax
                ? state.salaryMin === allValue || state.salaryMax === allValue
                  ? "面议"
                  : `${state.salaryMin}-${state.salaryMax}K`
                : "请选择期望薪资"
              }
            </Text>
            <GpFontIcon name="icon-a-jiantou_youda" size={40} className="text-placeholder" />
          </View>
        </View>
        <View className="px-[32px] pb-[48px] pt-[278px]">
          <Button onClick={handleSave} className={clsx("h-[96px] flex flex-row justify-center items-center rounded-[64px] text-white text-[32px]", fulfilled ? "bg-theme" : "bg-theme/40")}>
            开始找工作
          </Button>
        </View>
      </View>
      {renderSalaryPannel()}
    </GpContainer>
  )
}
